package com.manager.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.manager.pojo.TbCommodity;
import com.manager.service.StorageService;
import com.manager.vo.IDUtils;
import com.manager.vo.TbUserEx;
/**
 * 
 * @Title:  StorageControl.java     
 * @Description:    库存Controller
 * @author:      
 * @date:   2019年2月16日 下午4:57:48   
 * @version V1.0
 */
@Controller
public class StorageControl {
	
	@Autowired
	private StorageService storageService; 
	
	@RequestMapping("/storage-list")	//获取库存分页list
	public String getStorageList(Integer page,Integer rows,String s_type,String like,Integer flag,String start,String end,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		if(flag!=null && flag == 1 && !start.isEmpty() && !end.isEmpty()) {
			
			Date dstart = null;
			Date dend = null;
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				dstart = sdf.parse(start);
				dend = sdf.parse(end);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			tbUserEx = storageService.getStorageListByDateTime(page, rows, dstart, dend);
			
			tbUserEx.setFlag(flag);
			tbUserEx.setStart(start);
			tbUserEx.setEnd(end);
			model.addAttribute("tbUserEx", tbUserEx);
			
			return "storage-list";
		}
		
		//判断查询模式
		if(s_type == null || like==null || s_type.isEmpty() || like.isEmpty()) {
			
			s_type = null;
			like=null;
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		
		if( s_type!=null && s_type.equals("name")) {	//商品名称查询
			
			//like参数存在中文 进行转码
			like = like.trim();
			
			try {
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			
			//获取 商品名称分页
			tbUserEx = storageService.getStorageListByName(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("type")) {	//商品类型查询
			
			//like参数存在中文 进行转码
			like = like.trim();
			
			try {
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			
			//获取分页查询
			tbUserEx = storageService.getStorageListByType(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("SKU")) {	//根据SKU查询

			//获取分页查询
			like = like.trim();
			tbUserEx = storageService.getStorageListBySKU(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
		}else {
			
			//查询全部
			tbUserEx = storageService.getStorageList(page, rows);
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		//判断成功失败码
		if(tbUserEx.getCode()!=200) {
			return "storage-list";
		}
		
		//添加到model容器 方便前端访问查看
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "storage-list";
	}
	
	@RequestMapping("/storage-uploadimg")
	@ResponseBody			//图片上传函数处理
	public TbUserEx storageUploadImg(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		String webinf_root = request.getRealPath("/WEB-INF");
		
		webinf_root = webinf_root.concat("\\images\\temp\\");
		File dirFile = new File(webinf_root);
		
		if(!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
        String filename=""+new Date().getTime()+file.getOriginalFilename();
        webinf_root = webinf_root.concat(filename);
        
        File newFile=new File(webinf_root);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
			file.transferTo(newFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
		String arr[] =  webinf_root.split("WEB-INF");
		
		arr[1] ="."+arr[1];
		System.out.println(arr[1]);
		tbUserEx.setCode(200);
		tbUserEx.setMsg("图片上传成功");
		tbUserEx.setError(arr[1]);
		return tbUserEx;
		
	}


	//库存添加页面访问
	@RequestMapping("/storage-add")
	public String storageAdds() {
		return "storage-add";
	}
	
	@RequestMapping("/storageadd")
	@ResponseBody		//将上传的文件 路径 和信息  添加到数据库
	public TbUserEx storageAdd(TbCommodity tbCommodity,String datetime,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		//路径拼接
		String webinf_root = request.getRealPath("/WEB-INF");
		String web_img_path = tbCommodity.getImg();
		web_img_path = web_img_path.substring(1, web_img_path.length());
		String old_img = webinf_root.concat(web_img_path);
		String new_img  = old_img.replaceAll("temp", "upload");
		
		File oldFile=new File(old_img);
		File newFile = new File(new_img);
		
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
        	//文件拷贝临时文件复制到 upload目录
        	FileUtils.copyFile(oldFile, newFile);
		} catch (IllegalStateException e) {

			e.printStackTrace();
			tbUserEx.setCode(500);
	        tbUserEx.setError("库存添加异常");
	        return tbUserEx;
		} catch (IOException e) {

			e.printStackTrace();
			tbUserEx.setCode(500);
	        tbUserEx.setError("库存添加异常");
	        return tbUserEx;
		}
        
        //字符串分割 WEB-INF 取后面的路径存储到数据
		String arr[] = new_img.split("WEB-INF");
		System.out.println("."+arr[1]);
		//临时文件删除
		oldFile.delete();
		//添加到数据库
		tbCommodity.setImg("."+arr[1]);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
       
		try {
			date = sdf.parse(datetime);
			tbCommodity.setDtime(date);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
       
       tbCommodity.setSku(String.valueOf(IDUtils.genItemId()));
       tbCommodity.setDescription("");
       tbCommodity.setLess(0);
       tbCommodity.setMany(0);
       tbCommodity.setLesswarning(0);
       tbCommodity.setManywarning(0);
  
       try {
    	   tbUserEx = storageService.addStorage(tbCommodity);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tbUserEx.setCode(500);
            tbUserEx.setMsg("库存添加异常");
            return tbUserEx;
		}
		
		return tbUserEx;
	}
	
	@RequestMapping("/storageedit")
	@ResponseBody			//库存编辑
	public TbUserEx storageEdits(TbCommodity tbCommodity,String datetime,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		TbCommodity old_tbCommodity = null;
		
		try {
			old_tbCommodity = storageService.getTbCommodityById(tbCommodity.getId());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(!old_tbCommodity.getImg().equals(tbCommodity.getImg())) {
			
			//路径拼接
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbCommodity.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			String new_img  = old_img.replaceAll("temp", "upload");
			
			
			
			File oldFile=new File(old_img);
			File newFile = new File(new_img);
			
	        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	        try {
	        	//文件拷贝临时文件复制到 upload目录
	        	FileUtils.copyFile(oldFile, newFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("库存编辑异常");
		        return tbUserEx;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("库存编辑异常");
		        return tbUserEx;
			}
	        //字符串分割 WEB-INF 取后面的路径存储到数据
	       String arr[] = new_img.split("WEB-INF");
	       System.out.println("."+arr[1]);
	      
	       //临时文件删除
	       oldFile.delete();
			
	      
	       String data_old_img = old_tbCommodity.getImg();
			String old_web_img_path = data_old_img.substring(1, data_old_img.length());
			String data_old_img_path = webinf_root.concat(old_web_img_path);
			
			File old = new File(data_old_img_path);
			old.delete();
			tbCommodity.setImg("."+arr[1]);
			System.out.println("与数据库图片不一样");
		}else {
			System.out.println("与数据库图片一样");
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = sdf.parse(datetime);
			tbCommodity.setDtime(date);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try{
			tbUserEx = storageService.editExisStorage(tbCommodity);
		}catch(Exception e) {
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("库存编辑异常");
			return tbUserEx;
		}
		
		return tbUserEx;
	}
	
	@RequestMapping("/storage-edit")	//库存编辑页面访问通过id获取信息显示页面上
	public String storageEdit(Integer id,Model model) {
		
		TbCommodity tbCommodity = null;
		
		try{
			tbCommodity = storageService.getTbCommodityById(id);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		model.addAttribute("tbCommodity", tbCommodity);
		
		return "storage-edit";
	}
	
	@RequestMapping("/storage-del")
	@ResponseBody		//库存删除根据ID删除
	public TbUserEx storageDel(Integer id,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		Boolean result = false;
		
		try{
			
			TbCommodity tbCommodity = storageService.getTbCommodityById(id);
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbCommodity.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			File file = new File(old_img);
			file.delete();
			
			result = storageService.delStorage(id);
			
		}catch(Exception e) {
			
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("库存删除异常");
			return tbUserEx;
		}
		
		if(!result) {
			
			tbUserEx.setCode(400);
			tbUserEx.setError("库存删除失败");
			return tbUserEx;
		}
		
		tbUserEx.setCode(200);
		tbUserEx.setMsg("库存删除成功");
		
		return tbUserEx;
	}
	

	
	
	@RequestMapping("/less-list")			//缺货列表获取
	public String lessList(Integer page,Integer rows,String s_type,String like,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		//判断查询模式
		if(s_type == null || like==null || s_type.isEmpty() || like.isEmpty()) {
			
			s_type = null;
			like=null;
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		
		if( s_type!=null && s_type.equals("name")) {	//商品名称查询
			
			//like参数存在中文 进行转码
			like = like.trim();
			try {
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
			//获取 商品名称分页
			tbUserEx = storageService.getStorageListByName(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("type")) {	//商品类型查询
			
			//like参数存在中文 进行转码
			like = like.trim();
			try {
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  

			//获取分页查询
			tbUserEx = storageService.getStorageListByType(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("SKU")) {	//根据SKU查询

			//获取分页查询
			like = like.trim();
			tbUserEx = storageService.getStorageListBySKU(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
		}else {
			
			//查询全部
			tbUserEx = storageService.getLessList(page, rows);
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		//判断成功失败码
		if(tbUserEx.getCode()!=200) {
			return "less-list";
		}
		
		//添加到model容器 方便前端访问查看
		model.addAttribute("tbUserEx", tbUserEx);

		return "less-list";
	}
	
	@RequestMapping("/less-page")		//缺货值页面访问
	public String lessPage(Integer id,Model model) {
		
		TbCommodity tbCommodity = storageService.getTbCommodityById(id);
		
		model.addAttribute("tbCommodity", tbCommodity);
		
		return "less-page";
	}
	
	@RequestMapping("/lesspage")
	@ResponseBody				//缺货 值更变
	public TbUserEx lessPages(TbCommodity tbCommodity) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		Boolean result = false;
		
		if(tbCommodity.getLess()>0) {
			tbCommodity.setLesswarning(1);
		}else {
			tbCommodity.setLesswarning(0);
		}
	
		try {
			result = storageService.updataSetLessOrMany(tbCommodity);
		}catch(Exception e) {
			
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("警告值修改异常");
			return tbUserEx;
		}
		
		if(!result) {
			
			tbUserEx.setCode(400);
			tbUserEx.setError("警告值修改失败");
		}
		
		tbUserEx.setCode(200);
		tbUserEx.setMsg("警告值修改成功");
		
		return tbUserEx;
	}
	
	@RequestMapping("/many-list")		//滞销预警列表获取
	public String manyList(Integer page,Integer rows,String s_type,String like,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		//判断查询模式
		if(s_type == null || like==null || s_type.isEmpty() || like.isEmpty()) {
			
			s_type = null;
			like=null;
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		//商品名称查询
		if( s_type!=null && s_type.equals("name")) {
			
			//取出两侧空格
			like = like.trim();
			try {	//like参数存在中文 进行转码
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			//获取 商品名称分页
			tbUserEx = storageService.getStorageListByName(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("type")) {	//商品类型查询
			
			//取出两侧空格
			like = like.trim();
			try {	//like参数存在中文 进行转码
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  

			//获取分页查询
			tbUserEx = storageService.getStorageListByType(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("SKU")) {	//根据SKU查询
			
			//取出两侧空格
			like = like.trim();			//获取分页查询
			tbUserEx = storageService.getStorageListBySKU(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
		}else {
			
			//查询全部
			tbUserEx = storageService.getLessList(page, rows);
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		//判断成功失败码
		if(tbUserEx.getCode()!=200) {
			return "many-list";
		}
		
		//添加到model容器 方便前端访问查看
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "many-list";
	}
	
	@RequestMapping("/many-page")		//滞销设置 值页面访问
	public String manyPage(Integer id,Model model) {
		
		TbCommodity tbCommodity = storageService.getTbCommodityById(id);
		
		model.addAttribute("tbCommodity", tbCommodity);
		
		return "many-page";
	}
	
	@RequestMapping("/manypage")
	@ResponseBody				//滞销值更新
	public TbUserEx manyPages(TbCommodity tbCommodity) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		Boolean result = false;
		
		if(tbCommodity.getMany()>0) {
			tbCommodity.setManywarning(1);
		}else {
			tbCommodity.setManywarning(0);
		}
	
		try {
			result = storageService.updataSetLessOrMany(tbCommodity);
		}catch(Exception e) {
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("警告值修改异常");
			return tbUserEx;
		}
		
		if(!result) {
			tbUserEx.setCode(400);
			tbUserEx.setError("警告值修改失败");
		}
		
		tbUserEx.setCode(200);
		tbUserEx.setMsg("警告值修改成功");
		
		
		return tbUserEx;
	}
}
